package com.huluobo.a2112mvvmdouyindemo.collect;


import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.huluobo.a2112mvvmdouyindemo.R;
import com.huluobo.a2112mvvmdouyindemo.adapter.CollectAdapter;
import com.huluobo.a2112mvvmdouyindemo.databinding.FragmentCollectBinding;
import com.huluobo.mvvm_base.bean.VideoBeanResult;
import com.huluobo.mvvm_base.db.AppDBUtils;
import com.huluobo.mvvm_base.view.BaseMVVMFragment;

import java.util.ArrayList;
import java.util.List;

public class CollectFragment extends BaseMVVMFragment<FragmentCollectBinding, CollectViewModel> {

    private List<VideoBeanResult.VideoBean> videoBeanList = new ArrayList<>();

    private CollectAdapter collectAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_collect;
    }

    @Override
    protected void initData() {
        viewModel.getCollectVideos();

        viewModel.success.observe(this, videoBeans -> {
            videoBeanList.clear();
            videoBeanList.addAll(videoBeans);
            collectAdapter.notifyDataSetChanged();
        });

        viewModel.failed.observe(this, s -> {
            Log.i("TagA", "获取收藏列表失败:" + s);
        });
    }

    @Override
    protected void initView() {
        dataBinding.collectRv.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        collectAdapter = new CollectAdapter(videoBeanList);
        dataBinding.collectRv.setAdapter(collectAdapter);

        collectAdapter.addChildClickViewIds(R.id.item_collect_delete_btn);

        collectAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.item_collect_delete_btn) {
                AppDBUtils.getInstance().getVideoDao().deleteVideo(videoBeanList.get(position));
                collectAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected Class<CollectViewModel> getViewModel() {
        return CollectViewModel.class;
    }
}